package cn.org.eshow.service.impl;


import cn.org.eshow.bean.JsApiTicket;
import cn.org.eshow.bean.Token;
import cn.org.eshow.bean.query.WeixinValQuery;
import cn.org.eshow.common.page.Page;
import cn.org.eshow.dao.WeixinValDao;
import cn.org.eshow.model.WeixinVal;
import cn.org.eshow.service.WeixinValManager;
import cn.org.eshow.util.DateUtil;
import cn.org.eshow.util.WeixinUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.jws.WebService;
import java.util.Date;
import java.util.List;

@WebService(serviceName = "WeixinValService", endpointInterface = "cn.org.eshow.service.WeixinValManager")
@Service("weixinValManager")
public class WeixinValManagerImpl extends GenericManagerImpl<WeixinVal, Integer> implements WeixinValManager {

    @Autowired
    WeixinValDao weixinValDao;

    public WeixinValManagerImpl() {
    }

    @Autowired
    public WeixinValManagerImpl(WeixinValDao weixinValDao) {
        super(weixinValDao);
        this.weixinValDao = weixinValDao;
    }

    @Override
    public List<WeixinVal> list(WeixinValQuery query) {
        return weixinValDao.list(query);
    }

    @Override
    public Page<WeixinVal> search(WeixinValQuery query) {
        return weixinValDao.search(query);
    }

    public WeixinVal check(WeixinValQuery query) {
        List<WeixinVal> weixinVals = list(query);
        if (weixinVals.isEmpty()) {
            return null;
        }
        return weixinVals.get(0);
    }

    @Override
    public WeixinVal refresh(String category, String type) {
        // 获得AccessToken信息
        WeixinValQuery weixinValQuery = new WeixinValQuery();
        weixinValQuery.setCategory(category);
        weixinValQuery.setType(type);
        weixinValQuery.setEnabled(Boolean.TRUE);
        WeixinVal weixinVal = check(weixinValQuery);

        // 更换表中val信息
        if (weixinVal == null) {
            if ("accessToken".equals(type)) {
                Token token = null;
                if ("user".equals(category)) {
                    token = WeixinUtil.token(WeixinUtil.APP_Id, WeixinUtil.APP_SECRET);
                }
                if (token != null) {
                    if (token.getAccess_token() != null && token.getExpires_in() != null) {
                        weixinVal = new WeixinVal(category, type, token.getAccess_token(), Long.parseLong(token.getExpires_in()) * 1000);
                        weixinVal = weixinValDao.save(weixinVal);
                    }
                }
            }
            if ("jsApiTicket".equals(type)) {
                WeixinVal obj = refresh(category, "accessToken");
                JsApiTicket ticket = WeixinUtil.jsApiTicket(obj.getVal().trim());
                if (ticket != null) {
                    if (ticket.getTicket() != null && ticket.getExpires_in() != null) {
                        weixinVal = new WeixinVal(category, type, ticket.getTicket(), Long.parseLong(ticket.getExpires_in()) * 1000);
                        weixinVal = weixinValDao.save(weixinVal);
                    }
                }
            }
        } else {
            //判断accessToken是否还有10分钟过期
            long timeNow = DateUtil.dateToLong(new Date());// 当前时间
            long timeEnd = DateUtil.dateToLong(weixinVal.getUpdateTime());// 最后修改时间
            if ((timeNow - timeEnd) > (weixinVal.getExpiresIn() - 1000 * 60 * 10)) {//快要过期，要修改新的AccessToken
                //时间到了先更换accessToken，顺带更换jsApiTicket
                weixinValQuery.setType("accessToken");
                WeixinVal accessToken = check(weixinValQuery);
                Token token = null;
                if ("user".equals(category)) {
                    token = WeixinUtil.token(WeixinUtil.APP_Id, WeixinUtil.APP_SECRET);
                }
                if (token != null) {
                    if (token.getAccess_token() != null && token.getExpires_in() != null) {
                        accessToken.setUpdateTime(new Date());
                        accessToken.setVal(token.getAccess_token());
                        accessToken.setExpiresIn(Long.parseLong(token.getExpires_in()) * 1000);
                        accessToken = weixinValDao.save(accessToken);
                    }
                }
                JsApiTicket ticket = WeixinUtil.jsApiTicket(accessToken.getVal().trim());
                WeixinVal jsapiTicket = null;
                if (ticket != null) {
                    if (ticket.getTicket() != null && ticket.getExpires_in() != null) {
                        weixinValQuery.setType("jsApiTicket");
                        jsapiTicket = check(weixinValQuery);

                        jsapiTicket.setUpdateTime(new Date());
                        jsapiTicket.setVal(ticket.getTicket());
                        jsapiTicket.setExpiresIn(Long.parseLong(ticket.getExpires_in()) * 1000);
                        jsapiTicket = weixinValDao.save(jsapiTicket);
                    }
                }
                if ("accessToken".equals(type)) {
                    return accessToken;
                }
                if ("jsApiTicket".equals(type)) {
                    return jsapiTicket;
                }
            }
        }
        //没有过期的token、ticket
        Boolean flag = Boolean.FALSE;
        WeixinVal accessToken = null;
        if (!"accessToken".equals(type)) {
            weixinValQuery.setType("accessToken");
            accessToken = check(weixinValQuery);
            flag = WeixinUtil.groups(accessToken.getVal());
        } else {
            flag = WeixinUtil.groups(weixinVal.getVal());
        }
        //需要判断当前的accessToken是否能用，如果其他地方使用过需要重新保存一遍
        //使用获取分组接口判断accessToken判断是否可用
        if (!flag) {
            if (accessToken == null) {
                weixinValQuery.setType("accessToken");
                accessToken = check(weixinValQuery);
            }
            Token token = null;
            if ("user".equals(category)) {
                token = WeixinUtil.token(WeixinUtil.APP_Id, WeixinUtil.APP_SECRET);
            }
            if (token != null) {
                if (token.getAccess_token() != null && token.getExpires_in() != null) {
                    accessToken.setUpdateTime(new Date());
                    accessToken.setVal(token.getAccess_token());
                    accessToken.setExpiresIn(Long.parseLong(token.getExpires_in()) * 1000);
                    accessToken = weixinValDao.save(accessToken);
                }
            }
            JsApiTicket ticket = WeixinUtil.jsApiTicket(accessToken.getVal().trim());
            WeixinVal jsapiTicket = null;
            if (ticket != null) {
                if (ticket.getTicket() != null && ticket.getExpires_in() != null) {
                    weixinValQuery.setType("jsApiTicket");
                    jsapiTicket = check(weixinValQuery);

                    jsapiTicket.setUpdateTime(new Date());
                    jsapiTicket.setVal(ticket.getTicket());
                    jsapiTicket.setExpiresIn(Long.parseLong(ticket.getExpires_in()) * 1000);
                    jsapiTicket = weixinValDao.save(jsapiTicket);
                }
            }
            if ("accessToken".equals(type)) {
                return accessToken;
            }
            if ("jsApiTicket".equals(type)) {
                return jsapiTicket;
            }
        }
        return weixinVal;
    }
}